package com.hnucm.cooklife.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.ArrayMap;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.core.graphics.ColorUtils;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.JsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.hnucm.cooklife.R;
import com.hnucm.cooklife.adapter.EditStepAdapter;
import com.hnucm.cooklife.adapter.EditUsageAdapter;
import com.hnucm.cooklife.adapter.RecomAdapter;
import com.hnucm.cooklife.base.BaseActivity;
import com.hnucm.cooklife.base.BasePresenter;
import com.hnucm.cooklife.base.Utils;
import com.hnucm.cooklife.base.utils.LoginUtils;
import com.hnucm.cooklife.base.utils.ObjectToMapExample;
import com.hnucm.cooklife.bean.db.DishDetail;
import com.hnucm.cooklife.bean.db.Origin;
import com.hnucm.cooklife.bean.db.Step;
import com.hnucm.cooklife.bean.uploaddish.UpRece;
import com.hnucm.cooklife.contract.uploaddish.Contract;
import com.hnucm.cooklife.custom.UsageItemDecoration;
import com.hnucm.cooklife.presenter.upload.UploadDishPresenter;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class UploadDishActivity extends BaseActivity<Contract.IUploadDishView, UploadDishPresenter>
                                implements Contract.IUploadDishView {



    Map<String, Object> jsonParams = new HashMap<String, Object>() {
    };

    public static final int RESULT_OK  = -1;
    private static final int RC_CHOOSE_PHOTO = 1;
    private static final int RC_CHOOSE_PIC = 2;
    private static final int PRC_PHOTO_PICKER = 1;


    private Context mContext;
    private EditStepAdapter mStepAdapter;
    private List<Integer> mIntegerList = new ArrayList<>();

    private EditUsageAdapter mUsageAdapter;
    private List<Integer> mList = new ArrayList<>();

    private ItemTouchHelper mItemTouchHelper;

    @BindView(R.id.step_recycler)
    RecyclerView mStep;

    @BindView(R.id.add_step)
    TextView mAddStep;

    @BindView(R.id.usage_recycler)
    RecyclerView mUsage;

    @BindView(R.id.add_usage)
    TextView mAddUsage;

    @BindView(R.id.adjust_usage_select)
    TextView mAdjustSelect;

    @BindView(R.id.upload_dish_toolbar)
    Toolbar mToolbar;

    @BindView(R.id.post)
    TextView mPost;

    @BindView(R.id.dish_pic)
    ImageView mDishPic;

    @BindView(R.id.dish_name)
    EditText mDishName;

    @BindView(R.id.dish_desc)
    EditText mDishDesc;

    private ImageView currentImage;

    private DishDetail mDishDetail = new DishDetail();


    private Handler mHandler = new Handler(Looper.myLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            msg.getCallback().run();
            return false;
        }
    });

    @Override
    protected int getContentViewId() {
        return R.layout.activity_upload_dish;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        mContext = getApplicationContext();
        initItemTouchHelper();
        initData();
        initAdapter();
        initToolbar();
        initStatusBar();
    }

    private void initStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().setStatusBarColor(Utils.getColor(mContext));
        }
        if (ColorUtils.calculateLuminance(Utils.getColor(mContext)) >= 0.5) {
            // 设置状态栏中字体的颜色为黑色
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            // 跟随系统
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

    private void initToolbar() {
        mToolbar.setBackgroundColor(Utils.getColor(mContext));
        setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_back);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//            getSupportActionBar().setDisplayShowTitleEnabled(true);
        }
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initItemTouchHelper() {
        mItemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN |
                            ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                    final int swipeFlags = 0;
                    return makeMovementFlags(dragFlags, swipeFlags);
                } else {
                    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                    final int swipeFlags = 0;
                    return makeMovementFlags(dragFlags, swipeFlags);
                }
            }

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                //得到当拖拽的viewHolder的Position
                int fromPosition = viewHolder.getAdapterPosition();
                //拿到当前拖拽到的item的viewHolder
                int toPosition = target.getAdapterPosition();
                if (fromPosition < toPosition) {
                    for (int i = fromPosition; i < toPosition; i++) {
                        Collections.swap(mList, i, i + 1);
                    }
                } else {
                    for (int i = fromPosition; i > toPosition; i--) {
                        Collections.swap(mList, i, i - 1);
                    }
                }
                mUsageAdapter.notifyItemMoved(fromPosition, toPosition);
                return true;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {

            }
            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                super.onSelectedChanged(viewHolder, actionState);
                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE)
                    viewHolder.itemView.setBackgroundColor(Color.LTGRAY);
            }

            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                viewHolder.itemView.setBackgroundColor(0);

            }

            //重写拖拽不可用
            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }

        });

        mItemTouchHelper.attachToRecyclerView(mUsage);
    }

    private void initData() {
        mIntegerList.add(1);
        mIntegerList.add(2);
        mList.add(1);
        mList.add(2);
    }

    @OnClick(R.id.add_step)
    public void click(){
        mIntegerList.add(1);
        mStepAdapter.setStepList(mIntegerList);
    }

    @OnClick(R.id.add_usage)
    public void click1(){
        mList.add(1);
        mUsageAdapter.setIntegerList(mList);
    }

    @OnClick(R.id.adjust_usage_select)
    public void click3(){
        int childCount = mUsage.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = mUsage.getChildAt(i);
            ImageView delete = child.findViewById(R.id.delete_usage);
            ImageView adjust = child.findViewById(R.id.adjust_usage);
            if(delete.getVisibility() == View.GONE && adjust.getVisibility() == View.GONE){
                delete.setVisibility(View.VISIBLE);
                adjust.setVisibility(View.VISIBLE);
                mAddUsage.setVisibility(View.INVISIBLE);
            } else {
                delete.setVisibility(View.GONE);
                adjust.setVisibility(View.GONE);
                mAddUsage.setVisibility(View.VISIBLE);
            }
        }
    }

    @OnClick(R.id.post)
    public void click4(){
        int childCount = mUsage.getChildCount();
        List<Origin> tempOrigin = new ArrayList<>();
        for (int i = 0; i < childCount; i++) {
            View child = mUsage.getChildAt(i);
            EditText oriname = child.findViewById(R.id.ori_name);
            EditText orimuch = child.findViewById(R.id.ori_much);
            Origin origin = new Origin();
            origin.oriname = oriname.getText().toString();
            origin.orimuch = orimuch.getText().toString();
            tempOrigin.add(origin);
        }

        mDishDetail.originList.clear();
        mDishDetail.originList.addAll(tempOrigin);


        int stepCnt = mStep.getChildCount();
        List<Step> tempStep = new ArrayList<>();
        for (int i = 0; i < stepCnt; i++) {
            View child = mStep.getChildAt(i);
            ImageView steppic = child.findViewById(R.id.steppic);
            EditText stepdesc = child.findViewById(R.id.stepdesc);
            Step step = new Step();
            step.sdesc = stepdesc.getText().toString();
            tempStep.add(step);
        }
        mDishDetail.stepList.clear();
        mDishDetail.stepList.addAll(tempStep);

        mDishDetail.dishname = mDishName.getText().toString();
        mDishDetail.dishdesc = mDishDesc.getText().toString();


        jsonParams = ObjectToMapExample.convert(mDishDetail);

//        JSONObject jsonObject = new JSONObject(jsonParams);
//        String s = (new JSONObject(jsonParams)).toString();
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),(new JSONObject(jsonParams)).toString());

        mPresenter.uploadDish(body);
    }

    private void initAdapter() {
        LinearLayoutManager manager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mStep.setLayoutManager(manager);
        mStepAdapter = new EditStepAdapter(mContext,mIntegerList);
        mStep.setAdapter(mStepAdapter);

        //需要两个经理
        LinearLayoutManager manager1 = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mUsage.setLayoutManager(manager1);
        mUsageAdapter = new EditUsageAdapter(mContext,mList,mItemTouchHelper);
        mUsage.setAdapter(mUsageAdapter);
        mUsage.addItemDecoration(new UsageItemDecoration());

        mUsageAdapter.setOnItemClickListener(new RecomAdapter.onItemClickListener() {
            @Override
            public void onSeleClickListener(View view, int position) {
                mList.remove(position);
                mUsageAdapter.notifyItemRemoved(position);
                mUsageAdapter.setIntegerList(mList);
            }
        });

        mStepAdapter.setOnItemClickListener(new RecomAdapter.onItemClickListener() {
            @Override
            public void onSeleClickListener(View view, int position) {
                currentImage = (ImageView)view;
                choosePhoto();
            }
        });
    }


    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    public void choosePhoto(){
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(mContext, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "BGAPhotoPickerTakePhoto");

            Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(mContext)
//                        .cameraFileDir(mTakePhotoCb.isChecked() ? takePhotoDir : null) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
//                        .maxChooseCount(mPhotosSnpl.getMaxItemCount() - mPhotosSnpl.getItemCount()) // 图片选择张数的最大值
                    .selectedPhotos(null) // 当前已选中的图片路径集合
                    .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                    .build();
            startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);
        } else {
            EasyPermissions.requestPermissions(this, "图片选择需要以下权限:\n\n1.访问设备上的照片\n\n2.拍照", PRC_PHOTO_PICKER, perms);
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == RC_CHOOSE_PHOTO) {
             List<String> selectedPhotos = BGAPhotoPickerActivity.getSelectedPhotos(data);
             mHandler.post(new Runnable() {
                 @Override
                 public void run() {
                     Glide.with(mContext)
                             .load(selectedPhotos.get(0))
                             .fitCenter()
                             .centerCrop()
                             .into((ImageView) currentImage);
                 }
             });

//                Bitmap bitmap = BitmapFactory.decodeFile(file.getName());
//                Bitmap roundBitmap = toRoundBitmap(bitmap);
//                File roundFile = getFile(roundBitmap);
        } else if(resultCode == RESULT_OK && requestCode == RC_CHOOSE_PIC){
            List<String> selectedPhotos = BGAPhotoPickerActivity.getSelectedPhotos(data);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Glide.with(mContext)
                            .load(selectedPhotos.get(0))
                            .fitCenter()
                            .centerCrop()
                            .into(mDishPic);
                }
            });
        }
    }

    @OnClick(R.id.dish_pic)
    public void onClick(){
        choosePic();
    }

    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    public void choosePic(){
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(mContext, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "BGAPhotoPickerTakePhoto");

            Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(mContext)
//                        .cameraFileDir(mTakePhotoCb.isChecked() ? takePhotoDir : null) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
//                        .maxChooseCount(mPhotosSnpl.getMaxItemCount() - mPhotosSnpl.getItemCount()) // 图片选择张数的最大值
                    .selectedPhotos(null) // 当前已选中的图片路径集合
                    .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                    .build();
            startActivityForResult(photoPickerIntent, RC_CHOOSE_PIC);
        } else {
            EasyPermissions.requestPermissions(this, "图片选择需要以下权限:\n\n1.访问设备上的照片\n\n2.拍照", PRC_PHOTO_PICKER, perms);
        }
    }
    @Override
    protected UploadDishPresenter createPresenter() {
        return new UploadDishPresenter();
    }

    @Override
    public void onLoading() {

    }

    @Override
    public void onLoadingFailed() {

    }

    @Override
    public void onLoadSuccess() {
//        ToastUtils.showShort("好啦");
    }

    @Override
    public void onUploadDish(UpRece upRece) {
        if(upRece.getCode() == 0){
            ToastUtils.showShort("好啦");
        }
    }
}